package com.tang.script.syntax;

import cn.hutool.Hutool;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.tang.script.exceptions.ScriptException;
import com.tang.script.variable.Constant;
import com.tang.script.variable.Variable;
import com.tang.script.variable.VariablesContainer;
import com.tang.script.variable.VariablesType;

import java.util.*;

public class FakeVariableContainer implements VariablesContainer {

    Map<String, Integer> countMap = new HashMap<>();
    int count = 2;

    @Override
    public Object getValue(Constant constant) {
        VariablesType type = constant.getType();
        if (isList(constant.getValue())) {
            return createListByType(constant.getValue(), type);
        }
        return getRandomValueByType(type);
    }

    @Override
    public Object getValue(Variable variable) {
        VariablesType type = variable.getType();
        String variableName = variable.getValue();
        if (isList(variableName)) {
            return createListByType(variable.getValue(), type);
        }
        return getRandomValueByType(type);
    }

    private List<Object> createListByType(String fieldName, VariablesType type) {
        String formName = getFormName(fieldName);
        int count = -1;
        if (!countMap.containsKey(formName)) {
            countMap.put(formName, this.count++);
        }
        count = countMap.get(formName);

        return createListByType(count, fieldName, type);
    }

    private List<Object> createListByType(int count, String fieldName, VariablesType type) {
        LinkedList<Object> objects = new LinkedList<>();
        for (int i = 0; i < count; i++) {
            objects.add(getRandomValueByType(type));
        }
        return objects;
    }

    private String getFormName(String fieldName) {
        String[] split = fieldName.split("\\.");
        Set<Class<?>> allUtils = Hutool.getAllUtils();
        return split[0];
    }

    private boolean isList(String value) {
        String[] split = value.split("\\.");
        return split.length >= 2;
    }



    private Object getRandomValueByType(VariablesType type) {
        switch (type) {
            case number:
                return randomNumber();
            case string:
                return randomString();
            default:
                throw new ScriptException("不支持的类型: " + type);
        }
    }

    private Object randomNumber() {
        return RandomUtil.randomNumber();
    }

    private Object randomString() {
        return IdUtil.fastUUID();
    }
}
